package com.brush.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brush.common.constant.Constants;
import com.brush.common.constant.UserConstants;
import com.brush.common.core.domain.entity.SysMenu;
import com.brush.common.exception.ServiceException;
import com.brush.common.exception.database.RecordNotFoundException;
import com.brush.common.utils.MessageUtils;
import com.brush.common.utils.SecurityUtils;
import com.brush.system.domain.req.sysmenu.SysMenuAddReq;
import com.brush.system.domain.req.sysmenu.SysMenuEditReq;
import com.brush.system.domain.req.sysmenu.SysMenuReq;
import com.brush.system.domain.resp.sysmenu.SysMenuResp;
import com.brush.system.domain.vo.MetaVo;
import com.brush.system.domain.vo.RouterVo;
import com.brush.system.mapper.SysMenuMapper;
import com.brush.system.service.SysMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【sys_menu(菜单权限表)】的数据库操作Service实现
 * @createDate 2024-08-19 10:07:22
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
        implements SysMenuService {

    /**
     * 根据角色id集合查询权限集合
     *
     * @param roleIdSet
     * @return
     */
    @Override
    public Set<String> findPermissionsByRoleIds(Set<Long> roleIdSet) {
        return baseMapper.findPermissionsByRoleIds(roleIdSet);
    }

    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long userId) {
        List<SysMenu> menuList = null;
        // 超级管理员，查询所有的菜单
        if (SecurityUtils.getLoginUser().getPermissions().contains(Constants.ALL_PERMISSION)) {
            menuList = baseMapper.selectMenuTreeAll();
        } else {
            // 普通用户，根据普通用户查询
            menuList = baseMapper.selectMenuTreeByUserId(userId);
        }

        // 重新递归组装成 链表结构
        return getChildPerms(menuList, 0L);
    }

    /**
     * 根据parent_id查询子菜单
     *
     * @param dbList    数据库菜单集合
     * @param parent_id
     * @return
     */
    private List<SysMenu> getChildPerms(List<SysMenu> dbList, long parent_id) {
        List<SysMenu> allMenuList = new ArrayList<>();

        dbList.stream().filter(item -> item.getParentId().equals(0L)).forEach(item -> {
            // 递归查询子菜单，放到item.children 中 List<SysMenu>
            recursionFn(dbList, item);
            allMenuList.add(item);

        });
        return allMenuList;
    }

    /**
     * 递归查询子菜单
     *
     * @param dbList     数据库菜单集合
     * @param parentItem 上级菜单
     */
    private void recursionFn(List<SysMenu> dbList, SysMenu parentItem) {
        List<SysMenu> childList = dbList.stream().filter(item1 -> item1.getParentId().equals(parentItem.getMenuId())).collect(Collectors.toList());
        //能查询到子菜单
        if (!childList.isEmpty()) {
            parentItem.setChildren(childList);
            //继续循环子节点的子节点
            childList.forEach(row -> recursionFn(dbList, row));

        }
    }

    /**
     * 构建前端路由所需要的菜单
     * {
     * path: '',
     * component: Layout,
     * redirect: 'index',
     * // 二级路由
     * children: [
     * {
     * path: 'index',
     * component: () => import('@/views/index'),
     * name: 'Index',
     * meta: { title: '首页', icon: 'dashboard', affix: true }
     * }
     * ]
     * }
     *
     * @param menus
     * @return
     */
    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();

        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (Objects.nonNull(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(getRouteName(menu.getRouteName(), menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(getRouteName(menu.getRouteName(), routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }


    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            return StrUtil.EMPTY;
        }
        return getRouteName(menu.getRouteName(), menu.getPath());
    }

    /**
     * 获取路由名称，如没有配置路由名称则取路由地址
     *
     * @param routerName 路由名称
     * @param path       路由地址
     * @return 路由名称（驼峰格式）
     */
    public String getRouteName(String routerName, String path) {
        String name = StrUtil.isNotEmpty(routerName) ? routerName : path;
        return StringUtils.capitalize(name);
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS, Constants.WWW, ".", ":"},
                new String[]{"", "", "", "/", "/"});
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }


    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) &&
                ((menu.getPath().startsWith(Constants.HTTP)) || (menu.getPath().startsWith(Constants.HTTPS)));
    }

    /**
     * 是否为parent_view组件 (三级路由)
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }


    /**
     * 查询菜单集合
     *
     * @param req
     * @return
     */
    @Override
    public List<SysMenuResp> search(SysMenuReq req) {
        List<SysMenuResp> dbMenuList = new ArrayList<>();
        // 超级管理员，查询所有的菜单
        if (SecurityUtils.getLoginUser().getPermissions().contains(Constants.ALL_PERMISSION)) {
            dbMenuList = baseMapper.searchAllMenu(req);
        } else {
            // 普通用户，根据普通用户查询
            req.setUserId(SecurityUtils.getUserId());
            dbMenuList = baseMapper.searchMenu(req);
        }

        //构建树形菜单
        List<SysMenuResp> buildMenuList = new ArrayList<>();

        //得到所有的菜单id
        List<Long> tempList = dbMenuList.stream().map(SysMenuResp::getMenuId).collect(Collectors.toList());

        //循环遍历菜单
        for (SysMenuResp parent : dbMenuList) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(parent.getParentId())) {
                getChildPermsRecursion(dbMenuList, parent);
                buildMenuList.add(parent);
            }
        }

        //如果为空，则返回所有菜单
        if (buildMenuList.isEmpty()) {
            buildMenuList = dbMenuList;
        }

        return buildMenuList;
    }

    /**
     * 根据id查询菜单详细信息
     *
     * @param menuId
     * @return
     */
    @Override
    public SysMenuResp findById(Long menuId) {
        return baseMapper.findById(menuId);
    }

    /**
     * 根据角色ID查询权限
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByRoleId(Long roleId)
    {
        List<String> perms = this.baseMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId)
    {
        List<String> perms = this.baseMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public boolean edit(SysMenuEditReq req) {
        // 根据主键查询菜单信息
        SysMenuResp sysMenuResp = baseMapper.findById(req.getMenuId());
        if (Objects.isNull(sysMenuResp)) {
            throw new RecordNotFoundException();
        }

        // 校验 菜单名称是否已存在
        if (!req.getMenuName().equals(sysMenuResp.getMenuName())) {
            if (this.baseMapper.exists(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getMenuName, req.getMenuName()))) {
                throw new ServiceException(MessageUtils.message("sysmenu.menuName.exists"));
            }
        }

        BeanUtils.copyProperties(req, sysMenuResp);

        SysMenu sysMenu = new SysMenu();

        BeanUtils.copyProperties(sysMenuResp, sysMenu);

        sysMenu.setUpdateBy(SecurityUtils.getUsername());
        boolean res = this.updateById(sysMenu);

        return res;
    }

    @Override
    public boolean add(SysMenuAddReq req) {

        // 校验 菜单名称是否已存在
        if (this.baseMapper.exists(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getMenuName, req.getMenuName()))) {
            throw new ServiceException(MessageUtils.message("sysmenu.menuName.exists"));
        }

        // 校验 如果菜单为外链，则路由地址必须以http(s)开头
        if (UserConstants.YES_FRAME.equals(req.getIsFrame()) && !req.getPath().startsWith(Constants.HTTP) && !req.getPath().startsWith(Constants.HTTPS)) {
            throw new ServiceException(MessageUtils.message("sysmenu.path.not.http"));
        }

        SysMenu sysMenu = new SysMenu();
        BeanUtils.copyProperties(req, sysMenu);

        boolean save = this.save(sysMenu);

        return save;
    }

    /**
     * 递归获取子菜单
     *
     * @param dbMenuList
     * @param parent
     */
    private void getChildPermsRecursion(List<SysMenuResp> dbMenuList, SysMenuResp parent) {
        List<SysMenuResp> children = new ArrayList<>();

        dbMenuList.stream().filter(item -> item.getParentId().equals(parent.getMenuId()))
                .forEach(item -> {
                    getChildPermsRecursion(dbMenuList, item);
                    children.add(item);
                });

        if (!children.isEmpty()) {
            parent.setChildren(children);
        }

    }

}




